import { createAlova } from "alova";

import AdapterUniapp from "@alova/adapter-uniapp";
import CONFIG from "@/config.mjs";
import { clearToken, getToken } from "@/hooks/auth";

// 默认请求需要携带token
export const defultAlova = createAlova({
  baseURL: CONFIG.LOCATION_ORIGIN,
  timeout: 50000,
  localCache: null,
  ...AdapterUniapp(),
  beforeRequest,
  responded,
});
// 上传专用请求
export const uploadAlova = createAlova({
  ...AdapterUniapp(),
  beforeRequest,
  localCache: null,
  responded: (response) => {
    if (response.statusCode === 200) {
      return true;
    }
    throw new Error("上传失败");
  },
});
// 下载专用请求
export const downAlova = createAlova({
  baseURL: CONFIG.LOCATION_ORIGIN,
  ...AdapterUniapp(),
  beforeRequest,
});
let loadingTimer;
/**
 * 全局拦截器。设置请求头等操作
 * @param {Object} method
 */
function beforeRequest(method) {
  showLoading(method);
  method.config.headers.token = getToken();
  method.config.headers.fissionId = uni.getStorageSync("fissionId");
  method.config.headers.miniApp = CONFIG.WECHAT_APPID;
  method.config.headers.orderMechanismId = uni.getStorageSync("MID");
}
function showLoading(method) {
  if (method.meta?.loading === true) {
    loadingTimer = setTimeout(() => {
      uni.$k.showLoading(method.meta?.loadingText);
    }, method.meta?.delay || 400);
  }
}
function closeLoading() {
  if (loadingTimer) clearTimeout(loadingTimer);
  loadingTimer = null;
  setTimeout(() => {
    uni.$k?.hideLoading?.();
  }, 300);
}
/**
 * 全局结果拦截器，判断请求数据使用
 * @param {Object} response
 * @param method
 */
function responded(response, method) {
  const { statusCode, data } = response;
  if (statusCode >= 400) {
    uni.showToast({
      title: CONFIG.AJAX_ERROR_DEFAULT,
      icon: "none",
    });
    closeLoading();
    throw new Error("请求错误");
  }
  if (statusCode === 200) {
    switch (data?.code) {
      case 200:
        closeLoading();
        return data.data || null;
      case 401:
        clearToken();
        closeLoading();
        throw new Error(data.msg);
      case 4010:
        closeLoading();
        uni.reLaunch({
          url: '/pages/home/home',
        });
        throw new Error(data.msg);
      default:
        if (method.meta?.msg !== false) {
          uni.showToast({
            title: data.msg || CONFIG.AJAX_ERROR_DEFAULT,
            icon: 'none',
          });
        } else {
          closeLoading();
        }
        throw new Error(data.msg);
    }
  }
}
